from flask_restplus import Resource, Namespace, fields, marshal, reqparse
from common.decorators import catch_error
from common.responses import ok
from common import constant
from common.response_model import base_model, pagination_model
from common.request_parser import get_parser as base_get_parser
from app.user.decorators import token_required
from app.finance.account.model import Account
from app.finance.account import dao

api = Namespace('account')

# ---------- model ----------
account_model = base_model.inherit('account_model', {
    "account_type": fields.Integer(description='类型'),
})
account_paginate_model = pagination_model.inherit('account_paginate_model', {
    "items": fields.Nested(account_model)
})

# ---------- create parser ----------
create_parser = reqparse.RequestParser()
create_parser.add_argument('name', type=str, required=True, help='商品名称')
create_parser.add_argument('short_name', type=str, help='名称拼音缩写，默认不用填写')
create_parser.add_argument('account_type', type=int,
                           choices=[constant.AccountType.CASH.value,
                                    constant.AccountType.BANK_ACCOUNT.value,
                                    constant.AccountType.WECHAT_PAY.value,
                                    constant.AccountType.ALIPAY.value,
                                    constant.AccountType.OTHER.value],
                           required=True,
                           help='客户类别')
create_parser.add_argument('notes', type=str, help='备注')
create_parser.add_argument('is_active', type=bool, choices=[True, False], help='是否启用')

# ---------- get parser ----------
get_parser = base_get_parser.copy()
get_parser.replace_argument('sorted_by', type=str, choices=[
    'name', 'id'
], default='id', help='sorted_by')


class AccountsResource(Resource):
    @catch_error
    @token_required
    @api.expect(create_parser)
    def post(self):
        """创建"""
        args = create_parser.parse_args()
        new_obj = Account.create(**args, commit=True)
        return ok(data=marshal(new_obj, account_model),
                  message='create success')

    @catch_error
    @token_required
    @api.expect(get_parser)
    def get(self):
        """获取列表"""
        args = get_parser.parse_args()
        pagination = dao.get_by_page(**args)
        return ok(data=marshal(pagination, account_paginate_model),
                  message='get success')


# ---------- put parser ----------
put_parser = create_parser.copy()


class AccountResource(Resource):
    @catch_error
    @token_required
    def get(self, obj_id):
        """获取"""
        obj = Account.query.filter_by(id=obj_id).first()
        return ok(data=marshal(obj, account_model),
                  message='get success')

    @catch_error
    @token_required
    @api.expect(put_parser)
    def put(self, obj_id):
        """更新"""
        args = put_parser.parse_args()
        for key in list(args.keys()):
            if args.get(key) is None:
                del args[key]
        obj = Account.query.filter_by(id=obj_id).first()
        obj.update(**args, commit=True)
        return ok(data=marshal(obj, account_model),
                  message='update success')

    @catch_error
    @token_required
    def delete(self, obj_id):
        """获取"""
        obj = Account.query.filter_by(id=obj_id).first()
        delete_id = obj.hard_delete(commit=True)
        return ok(
            data={
                'id': delete_id
            },
            message='delete success')


# --------- route ----------
api.add_resource(AccountsResource, '/accounts')
api.add_resource(AccountResource, '/account/<int:obj_id>')

# 注册 response 文档
api.models[account_model.name] = account_model
